<template>
  <el-form
    :model="formData"
    ref="formRef"
    @submit.prevent
    :rules="formRules"
    label-width="100px"
  >
    <el-row>
      <el-col>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model.trim="formData.contractName"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="合同编号" prop="contractNum">
          <el-input v-model.trim="formData.contractNum"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="甲方单位" prop="partyA">
          <!-- <el-input v-model.trim="formData.partyA"></el-input> -->
          <el-select
            v-model="formData.partyA"
            clearable
            placeholder="请选择"
            style="width: 100%"
            ref="treeSelect"
          >
            <el-option :value="deptList">
              <el-tree
                id="tree-option"
                :data="deptList"
                accordion
                node-key="id"
                ref="partyATreeRef"
                highlight-current
                :props="defaultProps"
                @check-change="handleCheckChange"
                check-on-click-node
                :expand-on-click-node="false"
              ></el-tree>
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="甲方负责人" prop="directorAName">
          <!-- <el-input v-model.trim="formData.directorAName"></el-input> -->
          <el-select
            v-model="formData.directorAName"
            style="width: 100%"
            filterable
            clearable
            remote
            placeholder="请输入姓名搜索"
            :remote-method="getTableLeaderData"
            value-key="id"
          >
            <el-option
              id="default-option"
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="乙方单位" prop="partyB">
          <!-- <el-input v-model.trim="formData.partyB"></el-input> -->
          <el-select
            v-model="formData.partyB"
            style="width: 100%"
            filterable
            clearable
            remote
            placeholder="请输入名称搜索"
            :remote-method="searchCommanyData"
            value-key="id"
          >
            <el-option
              id="default-option"
              v-for="item in companyList"
              :key="item.id"
              :label="item.companyName"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="乙方负责人" prop="directorBName">
          <!-- <el-input v-model.trim="formData.directorBName"></el-input> -->
          <el-select
            v-model="formData.directorBName"
            style="width: 100%"
            filterable
            clearable
            remote
            placeholder="请输入姓名搜索"
            :remote-method="getTableLeaderDataB"
            value-key="id"
          >
            <el-option
              id="default-option"
              v-for="item in userListB"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="上传文档" prop="contractAttachmentArr">
          <el-upload
            name="uploadFile"
            multiple
            :accept="acceptTypes"
            :action="uploadComUrl"
            :headers="uploadHeaders"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-error="handleError"
            :file-list="defaultFileList"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePreview"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            v-model="formData.remark"
          ></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-row justify="end">
    <el-button @click="handleCancel">取 消</el-button>
    <el-button type="primary" @click="handleSubmit">确 定</el-button>
  </el-row>
</template>

<script lang="ts" setup>
import { ref, reactive, PropType, onMounted } from "vue";
import { ModeType } from "../types";
import { cloneDeep } from "lodash-es";
import { postDeptList } from "/@/api/dept";
import { postSysCompanyList } from "/@/api/organization";
import { getUsersForScience } from "/@/api/user";
import { useUpload } from "/@/hooks";
const {
  handleError,
  beforeAvatarUpload,
  uploadComUrl,
  acceptTypes,
  uploadHeaders,
  onInitFileList
} = useUpload();

const handlePreview = (item: any) => {
  window.open(
    `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
  );
};

const emit = defineEmits(["emitSubmit", "update:dialogFormVisible"]);

const formRef = ref<HTMLFormElement | null>(null) as any;
const treeSelect = ref<HTMLElement | null>(null) as any;

const props = defineProps({
  mode: {
    type: String as PropType<ModeType>,
    default: "Add"
  },
  contractInfo: {
    type: Object,
    default: () => {}
  },
  contractIndex: {
    type: Number,
    default: 0
  }
});

const partyATreeRef = ref<HTMLElement | null>(null) as any;

const defaultProps = {
  children: "children",
  label: "deptDescShrt",
  id: "id",
  disabled: "false"
};

let formData = reactive({
  contractName: "",
  contractNum: "",
  contractAttachmentArr: [],
  partyA: "",
  // partyAId: "", 后端字段缺失
  partyB: null,
  // partyBId: "", 后端字段缺失
  directorAName: null,
  directorA: "",
  directorBName: null,
  directorBId: "",
  remark: ""
});

let deptList = ref([]);
let companyList = ref([]);
let userList = ref([]);
let userListB = ref([]);

const formRules = ref({
  contractName: [
    { required: true, message: "请输入合同名称", trigger: "change" }
  ],
  contractNum: [
    { required: true, message: "请输入合同编号", trigger: "change" }
  ],
  contractAttachmentArr: [
    { required: true, message: "请上传附件", trigger: "change" }
  ],
  partyA: [{ required: true, message: "请填写甲方单位", trigger: "change" }],
  partyB: [{ required: true, message: "请填写乙方单位", trigger: "change" }],
  directorAName: [
    { required: true, message: "请填写甲方负责人", trigger: "change" }
  ],
  directorBName: [
    { required: true, message: "请填写乙方负责人", trigger: "change" }
  ]
});

/* 上传 -- start */

let defaultFileList = ref([]);

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
  formData.contractAttachmentArr = formData.contractAttachmentArr.filter(
    item => {
      const uuid = file.response ? file.response.data.uuidFile : file.uuidFile;
      return item.uuidFile !== uuid;
    }
  );
};

const handleSuccess = (res, file, fileList) => {
  if (res.code === 200) {
    defaultFileList.value = fileList;
    formData.contractAttachmentArr.push(res.data);
  }
  formRef.value.clearValidate();
};

/* 上传 -- end */

const handleSubmit = async (): Promise<any> => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) return;
  const copyFormData = cloneDeep(formData);
  copyFormData.partyB = formData.partyB.companyName;
  copyFormData.directorAName = formData.directorAName.name;
  copyFormData.directorA = formData.directorAName.id;

  copyFormData.directorBName = formData.directorBName.name;
  copyFormData.directorBId = formData.directorBName.id;

  emit("emitSubmit", {
    mode: props.mode,
    index: props.contractIndex,
    info: copyFormData
  });
};

const handleCancel = () => {
  emit("update:dialogFormVisible", false);
};

const initDeptList = async () => {
  const { code, data } = await postDeptList({
    pageSize: 0
  });
  if (code === 200) {
    deptList.value = data;
  }
};

const handleCheckChange = () => {
  const res = partyATreeRef.value.getCurrentNode();
  formData.partyA = [res][0].deptDescShrt;
  // formData.partyAId = [res][0].id;
  treeSelect.value.blur();
};

const initCommanyData = () => {
  getDeptData();
};

const searchCommanyData = (query = "") => {
  if (!query) {
    companyList.value = [];
    return;
  }
  getDeptData(query);
};

async function getDeptData(query = "") {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await postSysCompanyList(params);
    if (code === 200) {
      companyList.value = data.list.map(item => {
        return { id: item.id, companyName: item.companyName };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

async function getTableLeaderData(query = "") {
  if (!query) {
    userList.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      nameLike: query
    };
    const { code, data } = await getUsersForScience(params);
    if (code === 200) {
      userList.value = data.list.map(item => {
        return {
          id: item.id,
          name: item.name + (item.deptName ? "-" + item.deptName : "-无")
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

async function getTableLeaderDataB(query = "") {
  if (!query) {
    userList.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      nameLike: query
    };
    const { code, data } = await getUsersForScience(params);
    if (code === 200) {
      userListB.value = data.list.map(item => {
        return {
          id: item.id,
          name: item.name + (item.deptName ? "-" + item.deptName : "-无")
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

initDeptList();
initCommanyData();

onMounted(() => {
  if (props.mode === "Edit") {
    formData.contractName = props.contractInfo.contractName;
    formData.contractNum = props.contractInfo.contractNum;
    formData.contractAttachmentArr = props.contractInfo.contractAttachmentArr;
    formData.partyA = props.contractInfo.partyA;
    // formData.partyAId = props.contractInfo.partyAId;
    formData.partyB = props.contractInfo.partyB;
    // formData.partyBId = props.contractInfo.partyBId;
    formData.directorAName = {
      id: +props.contractInfo.directorA,
      name: props.contractInfo.directorAName
    };
    formData.directorA = props.contractInfo.directorA;
    userList.value = [formData.directorAName];
    formData.directorBName = {
      id: +props.contractInfo.directorA,
      name: props.contractInfo.directorBName
    };
    formData.directorBId = props.contractInfo.directorBId;
    userListB.value = [formData.directorBName];
    formData.remark = props.contractInfo.remark;

    defaultFileList.value = onInitFileList(
      props.contractInfo.contractAttachmentArr
    );
  }
});
</script>

<style lang="scss" scoped>
.el-select-dropdown__item {
  height: auto;
  // min-height: 100px;
  // max-height: 274px;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}
.el-select-dropdown_item.selected {
  font-weight: normal;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

// #tree-option
#tree-option :deep .el-tree-node__content {
  height: auto;
  padding: 0 10px;
}
// #tree-option :deep .el-select-dropdown__list {
//   padding: 0 6px;
// }
#tree-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  margin-right: 10px;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
#default-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  // margin-right: 10px;
}

#default-option {
  padding: 0 10px;
}
</style>
